package com.cy.model.dingtalk;

import com.cy.BasicModel;
import com.cy.ext.plugin.tablebind.TableBind;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import org.apache.commons.lang3.time.DateUtils;

import java.util.Calendar;
import java.util.Date;

@TableBind(tableName="dd_config",pkName = "name")
public class DdConfig extends BasicModel<DdConfig> {
    public static final DdConfig dao = new DdConfig();
    public static final String SELECT_ALL = "`name`,`value`,`last_update_time`,`expire_time`";

    private static final String JSAPI_TICKET = "jsapi_ticket";

    public DdConfig getJsapiTicket(){
        return findFirst("select * from dd_config where name = ?", JSAPI_TICKET);
    }

    /**
     * 检查是否可更新
     * @return true 需要更新 false 不需要更新
     */
    public boolean isUpdatableTicket(){
        Date currentTime = new Date();
        /*当前时间在过期时间前30分钟以内更新*/
        Date expireTime = getExpireTime();
        Date beforeTimeRangeMin = DateUtils.addMinutes(expireTime, -30);
        return currentTime.after(beforeTimeRangeMin);
    }

    public boolean saveJsapiTicket() {
        Date lastUpdateTime = new Date();
        Calendar expireTime = Calendar.getInstance();
        expireTime.setTime(lastUpdateTime);
        //2小时过期
        expireTime.add(Calendar.HOUR_OF_DAY, 2);
        Record record = new Record();
        record.set("name", JSAPI_TICKET);
        record.set("value", getValue());
        record.set("last_update_time", lastUpdateTime);
        record.set("expire_time", expireTime.getTime());
        return Db.save(getTableName(), record);
    }

    public boolean updateJsapiTicket() {
        Date lastUpdateTime = new Date();
        Calendar expireTime = Calendar.getInstance();
        expireTime.setTime(lastUpdateTime);
        //2小时过期
        expireTime.add(Calendar.HOUR_OF_DAY, 2);
        Record record = new Record();
        record.set("name", JSAPI_TICKET);
        record.set("value", getValue());
        record.set("last_update_time", lastUpdateTime);
        record.set("expire_time", expireTime.getTime());
        return Db.update(getTableName(), "name", record);
    }
            
    public DdConfig setName(String name){
        return this.set("name",name);
    }

    public String getName(){
        return this.getStr("name");
    }
        
    public DdConfig setValue(String value){
        return this.set("value",value);
    }

    public String getValue(){
        return this.getStr("value");
    }
        
    public DdConfig setLastUpdateTime(Date lastUpdateTime){
        return this.set("last_update_time",lastUpdateTime);
    }

    public Date getLastUpdateTime(){
        return this.get("last_update_time");
    }
        
    public DdConfig setExpireTime(Date expireTime){
        return this.set("expire_time",expireTime);
    }

    public Date getExpireTime(){
        return this.get("expire_time");
    }
}